<template>
  <div class="login">
    <div class="login_box">
      <div class="content-layout">
        <div class="login-box-warp">
          <div class="login-box-war-logo">
            <img src="../assets/login-logo.png" style="width: 60px" />
          </div>

          <div v-if="isLogin">
            <el-form
              ref="loginFormRef"
              :rules="loginRules"
              :model="loginForm"
              class="login_form"
              label-width="0"
            >
              <!-- 账号 -->
              <el-form-item prop="usercode">
                <el-input
                  v-model="loginForm.usercode"
                  class="w-50 m-2"
                  size="large"
                  placeholder="请输入账号"
                  :prefix-icon="User"
                />
              </el-form-item>
              <!-- 密码 -->
              <el-form-item prop="password">
                <el-input
                  v-model="loginForm.password"
                  class="w-50 m-2"
                  size="large"
                  placeholder="请输入密码"
                  :prefix-icon="Lock"
                  type="password"
                />
              </el-form-item>
              <!-- 按钮 -->
              <el-form-item class="btns">
                <el-button type="primary" @click="submitLogin()">
                  登录
                </el-button>
                <!-- <el-button type="info" @click="resetLoginForm()">重置</el-button> -->
              </el-form-item>
            </el-form>
          </div>

          <div v-if="!isLogin">
            <el-form
              ref="registerForm"
              :rules="rules"
              :model="registerForm"
              class="login_form"
              label-position="right"
              label-width="0"
            >
              <el-form-item prop="userName">
                <el-input
                  v-model="registerForm.userName"
                  class="w-50 m-2"
                  size="large"
                  placeholder="请输入用户名称"
                  :prefix-icon="User"
                />
              </el-form-item>
              <!-- <el-form-item prop="userName">
                <el-upload
                  class="avatar-uploader"
                  :show-file-list="false"
                  v-model="registerForm.imgFile"
                >
                  <img v-if="imageUrl" :src="imageUrl" class="avatar" />
                  <el-icon v-else class="avatar-uploader-icon">
                    <Plus />
                  </el-icon>
                </el-upload>
              </el-form-item> -->
              <el-form-item prop="userCode">
                <el-input
                  v-model="registerForm.userCode"
                  class="w-50 m-2"
                  size="large"
                  placeholder="请输入账号"
                  :prefix-icon="User"
                />
              </el-form-item>

              <el-form-item prop="password">
                <el-input
                  v-model="registerForm.password"
                  class="w-50 m-2"
                  size="large"
                  placeholder="密码"
                  :prefix-icon="User"
                  type="password"
                />
              </el-form-item>

              <el-form-item prop="checkPass">
                <el-input
                  type="password"
                  placeholder="确认密码"
                  v-model="registerForm.checkPass"
                  autocomplete="off"
                  :prefix-icon="User"
                ></el-input>
              </el-form-item>
              <el-form-item prop="mobilePhone">
                <el-input
                  v-model="registerForm.mobilePhone"
                  class="w-50 m-2"
                  size="large"
                  placeholder="电话号码"
                  :prefix-icon="User"
                />
              </el-form-item>
              <!-- <el-form-item prop="description">
                <el-input
                  v-model="registerForm.description"
                  class="w-50 m-2"
                  size="large"
                  placeholder="简介"
                  :prefix-icon="User"
                />
              </el-form-item> -->

              <el-form-item prop="role">
                <el-select
                  v-model="registerForm.role"
                  filterable
                  placeholder="选择角色"
                >
                  <el-option label="管理员" value="1"></el-option>
                  <el-option label="普通用户" value="2"></el-option>
                </el-select>
              </el-form-item>

              <el-form-item class="btns">
                <el-button type="primary" @click="submitRegister()">
                  {{ isLogin ? '登录' : '注册' }}
                </el-button>
                <!-- <el-button type="info" @click="resetLoginForm()">重置</el-button> -->
              </el-form-item>
            </el-form>
          </div>

          <div @click="changeType()" class="login-text">
            >> {{ isLogin ? '注册' : '登录' }}
          </div>
        </div>
      </div>

      <div class="register">
        <!-- <p>还没有账号？去<router-link to="/register">注册</router-link></p> -->
        <!-- <p>回到<router-link to='/home'>首页</router-link></p> -->
      </div>
    </div>
  </div>
</template>
<script setup>
import { User, Lock } from '@element-plus/icons-vue'
</script>
<script>
import { Search } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { register, login } from '../api/user.js'
import dayjs from 'dayjs'

export default {
  name: 'Login',
  data() {
    var validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'))
      } else {
        if (this.registerForm.checkPass !== '') {
          this.$refs.registerForm.validateField('checkPass')
        }
        callback()
      }
    }
    var validatePass2 = (rule, value, callback) => {
      if (value == '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.registerForm.password) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    return {
      isLogin: true,
      //表单数据对象
      loginForm: {
        usercode: '',
        password: ''
      },
      //验证对象
      loginRules: {
        //校验用户名
        usercode: [
          { required: true, message: '账号为必填项！', trigger: 'blur' },
          {
            max: 12,
            message: '长度在 小于 12 个字符',
            trigger: 'blur'
          }
        ],
        password: [
          { required: true, message: '密码为必填项！', trigger: 'blur' },
          { min: 2, max: 15, message: '长度在 2 ~ 15 个字符', trigger: 'blur' }
        ]
      },
      registerForm: {
        userName: '',
        userCode: '',
        password: '',
        mobilePhone: '',
        description: '',
        role: ''
      },
      rules: {
        password: [{ validator: validatePass, trigger: 'blur' }],
        checkPass: [{ validator: validatePass2, trigger: 'blur' }]
      }
    }
  },
  methods: {
    //切换登录和注册
    changeType() {
      console.log('isLogin', this.isLogin)
      this.isLogin = !this.isLogin
    },
    //重置表单
    resetLoginForm() {
      this.$refs.loginFormRef.resetFields()
    },

    async submitLogin() {
      //1、验证校验规则
      this.$refs.loginFormRef.validate(async (valid) => {
        if (!valid) return // 验证失败
        // const { data: res } = await this.$http.post("login", this.loginForm); // 访问后台
        const values = {
          ...this.loginForm,
          password: this.loginForm.password
        }
        login(values).then((res) => {
          console.log('res', res)
          if (res.code !== 200) {
            ElMessage({
              message: '登录失败',
              type: 'error'
            })
            return
          }
          // ElMessage({
          //   message: '登录成功',
          //   type: 'success'
          // })
          window.localStorage.setItem('user_info', JSON.stringify(res.data))
          this.$router.push('/')
          // localStorage.setItem('token', res.token)
          // getUserInfo().then((res) => {
          //   window.localStorage.setItem('user_info', JSON.stringify(res))

          //   if (res.post_id == 1 || res.post_id == 2) {
          //     this.$router.push({
          //       path: 'home'
          //     })

          //     window.location.reload()
          //   } else {
          //     this.$router.push({
          //       path: 'clock'
          //     })
          //     window.location.reload()
          //   }
          // })
        })
      })
    },

    async submitRegister() {
      this.$refs.registerForm.validate(async (valid) => {
        if (!valid) return
        delete this.registerForm.checkPass
        const params = {
          ...this.registerForm,
          status: 1,
          id: Math.floor(Math.random() * (999999 - 100000 + 1)) + 100000,
          role: Number(this.registerForm.role)
          // createTime: dayjs().format('YYYY-MM-DD HH:mm:ss')
        }
        register(params).then((res) => {
          if (res.code === 200) {
            this.isLogin = true
            ElMessage({
              message: '注册成功',
              type: 'success'
            })
          }
        })
      })
    },

    //重置按钮
    resetLoginForm() {
      this.loginForm.password = ''
      this.loginForm.usercode = ''
    }
  }
}
</script>

<style lang="less" scoped>
.login_box {
  background: url('../assets/login.gif');
  position: absolute;
  z-index: 9;
  top: 50%;
  left: 100px;
  background-size: cover;
  background-repeat: no-repeat;
  background-position: 0;
  width: 45%;
  height: 600px;
  transform: translate(0, -50%);
  .content-layout {
    width: 1200px;
    margin: 0 auto;
    overflow: hidden;
    position: relative;
    height: 600px;
    z-index: 999;
  }

  .login-box-warp {
    position: absolute;
    top: 50%;
    right: 0;
    width: 350px;
    padding: 40px 20px;
    color: #6c6c6c;
    background: #fff;
    background-color: hsla(0, 0%, 100%, 0.9);
    border-radius: 16px;
    box-shadow: 0px 12px 32px 4px rgba(0, 0, 0, 0.04),
      0px 8px 20px rgba(0, 0, 0, 0.08);
    transform: translate(0, -50%);
  }

  .login-box-war-logo {
    display: flex;
    justify-content: center;
    margin: 30px;
  }

  .login-text {
    cursor: pointer;
    color: #3370ff;
    font-size: 14px;
  }
}
.el-button--primary {
  width: 100%;
}
</style>
